package com.example.arrange;

import com.example.util.CommonUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class AllOfDemo2 {
    public static void main(String[] args) {
        CommonUtils.printThreadLog("main start");

        List<String> newsPathList = Arrays.asList("news1.txt", "news2.txt", "news3.txt");
        List<CompletableFuture<String>> readFileFutureList = newsPathList.stream().map(AllOfDemo2::readFileFuture).collect(Collectors.toList());

        CommonUtils.printThreadLog("main continue");

        CompletableFuture[] readFileFutureArray = readFileFutureList.toArray(new CompletableFuture[readFileFutureList.size()]);
        CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(readFileFutureArray);
        CompletableFuture<Long> future = allOfFuture.thenApply(v -> readFileFutureList.stream().map(CompletableFuture::join).filter(content -> content.contains("CompletableFuture")).count());

        Long count = future.join();
        System.out.println(count);

        CommonUtils.printThreadLog("main end");
    }

    private static CompletableFuture<String> readFileFuture(String path) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        });
    }

}
